#!/bin/bash
# 钩子框架演示脚本

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
RESET='\033[0m'

# 设置工作目录
ROOT_DIR=$(pwd)
HOOK_LIB="$ROOT_DIR/lib/libhook.so"
DEMO_PLUGIN="$ROOT_DIR/plugins/demo_plugin/plugin.so"
DEMO_APP="$ROOT_DIR/examples/hook_demo"

echo -e "${BLUE}===== 钩子框架演示 =====${RESET}"
echo ""

# 检查必要文件是否存在
if [ ! -f "$HOOK_LIB" ]; then
    echo -e "${RED}错误: 钩子框架库不存在: $HOOK_LIB${RESET}"
    echo "请先编译框架库: make"
    exit 1
fi

# 编译演示插件
echo -e "${YELLOW}编译演示插件...${RESET}"
if [ ! -d "$ROOT_DIR/plugins/demo_plugin" ]; then
    mkdir -p "$ROOT_DIR/plugins/demo_plugin"
fi
make -C plugins/demo_plugin

# 编译演示应用
echo -e "${YELLOW}编译演示应用...${RESET}"
gcc -o $DEMO_APP examples/hook_demo.c -Wall -pthread

# 设置环境变量
export LD_LIBRARY_PATH="$ROOT_DIR/lib:$LD_LIBRARY_PATH"
export HOOK_LOG_LEVEL="INFO"
export DEMO_PLUGIN_LOG_LEVEL="INFO"
export DEMO_PLUGIN_LOG_FILE="/tmp/demo_plugin.log"
export DEMO_PLUGIN_MONITOR_FILE="1"
export DEMO_PLUGIN_MONITOR_NETWORK="1"
export DEMO_PLUGIN_MONITOR_PROCESS="1"
export DEMO_PLUGIN_MONITOR_MEMORY="1"

# 提示用户
echo ""
echo -e "${GREEN}准备运行演示程序...${RESET}"
echo "环境配置:"
echo "  - 钩子库: $HOOK_LIB"
echo "  - 插件: $DEMO_PLUGIN"
echo "  - 应用: $DEMO_APP"
echo "  - 日志级别: $HOOK_LOG_LEVEL"
echo "  - 插件日志文件: $DEMO_PLUGIN_LOG_FILE"
echo ""
echo -e "${YELLOW}运行演示程序...${RESET}"

# 运行演示应用
LD_PRELOAD="$HOOK_LIB:$DEMO_PLUGIN" $DEMO_APP

# 查看插件日志
echo ""
echo -e "${BLUE}演示完成!${RESET}"
echo -e "${YELLOW}插件日志内容 (来自 $DEMO_PLUGIN_LOG_FILE):${RESET}"
if [ -f "$DEMO_PLUGIN_LOG_FILE" ]; then
    echo -e "${GREEN}--------------------------------${RESET}"
    cat "$DEMO_PLUGIN_LOG_FILE" | tail -n 25
    echo -e "${GREEN}--------------------------------${RESET}"
    echo -e "完整日志可查看: ${BLUE}$DEMO_PLUGIN_LOG_FILE${RESET}"
else
    echo -e "${RED}插件日志文件不存在${RESET}"
fi 